package com.um.jdy.mp.user.manager;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.util.ReUtil;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.commons.service.MobileService;
import com.um.jdy.common.member.enums.CodeKey;
import com.um.jdy.common.platform.code.LoginCode;
import com.um.jdy.common.platform.code.PartnersCode;
import com.um.jdy.common.platform.entity.po.Merchant;
import com.um.jdy.common.platform.entity.po.MerchantLog;
import com.um.jdy.common.platform.service.AppSettingService;
import com.um.jdy.common.platform.service.MerchantLogService;
import com.um.jdy.common.platform.service.MerchantService;
import com.um.jdy.mp.user.entity.dto.BindWXDTO;
import com.um.jdy.mp.user.entity.dto.MobileDTO;
import com.um.jdy.mp.user.entity.dto.ResetPasswordDTO;
import com.um.jdy.mp.user.entity.vo.MerchantVO;
import com.um.jdy.mp.user.entity.vo.SigninVO;
import com.um.jdy.mp.user.service.SessionUserService;
import com.um.springboot.starter.code.CommonCode;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.service.CacheService;
import com.um.springboot.starter.utils.DesEncrypter;
import com.um.springboot.starter.utils.RSAUtil;
import com.um.springboot.starter.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 管理类：手机
 *
 * @author cs
 * 日期 2023/5/23
 * 版权所有 广州优匠科技有限公司
 */
@Component
public class MobileManager extends BaseManager<MerchantService> {

    @Autowired
    CacheService cacheService;

    @Autowired
    MerchantService merchantService;

    @Autowired
    MerchantLogService merchantLogService;

    @Autowired
    MobileService mobileService;

    @Autowired
    SessionUserService sessionUserService;


    /**
     * 发送短信验证码
     *
     * @param prefix
     * @param mobile
     */
    public void sendCode(CodeKey prefix, String mobile) {
        if(!ReUtil.isMatch(RegexPool.MOBILE, mobile)){
            throw new ServiceException(LoginCode.MobileIllegal);
        }

        if (CodeKey.Signup == prefix) {
            if(null != merchantService.getEntity("mobile", mobile)){
                throw new ServiceException(LoginCode.MobileExist);
            }
        }

        if (CodeKey.Signin == prefix || CodeKey.FindPwd == prefix || CodeKey.BindWX == prefix) {
            if(null == merchantService.getEntity("mobile", mobile)){
                throw new ServiceException(LoginCode.MobileNotExist);
            }
        }
        mobileService.sendCode(prefix, mobile,getComId());
    }

    /**
     * 绑定微信
     *
     * @param bindwxDTO
     */
    public SigninVO bindwx(BindWXDTO bindwxDTO) {
        if(!ReUtil.isMatch(RegexPool.MOBILE, bindwxDTO.getMobile())){
            throw new ServiceException(LoginCode.MobileIllegal);
        }

        mobileService.checkCode(CodeKey.BindWX, bindwxDTO.getMobile(), bindwxDTO.getCode());

        Merchant merchant = merchantService.getEntity("mobile", bindwxDTO.getMobile());
        if (null == merchant) {
            throw new ServiceException(LoginCode.MobileNotExist);
        }

        if(merchant.getIsEnable().equals(YesOrNo.No.name())){
            throw new ServiceException(LoginCode.AccountDisabled);
        }

        merchant.setMobile(bindwxDTO.getMobile());
        merchant.setMpOpenId(bindwxDTO.getOpenid());
        merchant.setWxNickName(StringUtil.getTrim(bindwxDTO.getNickname(),"未知昵称"));
        merchant.setLogo(StringUtil.getTrim(bindwxDTO.getHeadimgurl(), ""));
        merchant.setCreateTime(DateUtil.date());
        merchantService.saveEntity(merchant);

        mobileService.expireCode(CodeKey.BindWX, bindwxDTO.getMobile());

        StpUtil.login(merchant.getPlatformMerchantId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        SigninVO mobileSigninVO = new SigninVO();
        mobileSigninVO.setToken(tokenInfo.getTokenValue());
        mobileSigninVO.setMerchant(BeanUtil.toBean(merchant, MerchantVO.class));
        return mobileSigninVO;
    }

    /**
     * 手机登录
     *
     * @param mobileDTO
     */
    public SigninVO signin(MobileDTO mobileDTO) {
        if(!ReUtil.isMatch(RegexPool.MOBILE, mobileDTO.getMobile())){
            throw new ServiceException(LoginCode.MobileIllegal);
        }

        //检查验证码
        mobileService.checkCode(CodeKey.Signin, mobileDTO.getMobile(), mobileDTO.getCode());

        Merchant merchant = merchantService.getEntity("mobile", mobileDTO.getMobile());
        if (null == merchant) {
            throw new ServiceException(LoginCode.MobileNotExist);
        }
        if (YesOrNo.No.name().equals(merchant.getIsEnable())) {
            throw new ServiceException(CommonCode.AccountDisabled);
        }

//        if (StrUtil.isEmpty(merchant.getMpOpenId())) {
//            throw new ServiceException(LoginCode.AuthError);
//        }

        MerchantLog loginLog = new MerchantLog();
        loginLog.setPlatformMerchantId(merchant.getPlatformMerchantId());
        loginLog.setCreateTime(new Date());
        loginLog.setComId(merchant.getComId());
        merchantLogService.add(loginLog);

        mobileService.expireCode(CodeKey.Signin, mobileDTO.getMobile());

        StpUtil.login(merchant.getPlatformMerchantId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        SigninVO mobileSigninVO = new SigninVO();
        mobileSigninVO.setToken(tokenInfo.getTokenValue());
        mobileSigninVO.setMerchant(BeanUtil.toBean(merchant, MerchantVO.class));
        return mobileSigninVO;
    }

    /**
     * 验证原手机号
     *
     * @param mobileDTO
     */
//    public void verify(MobileDTO mobileDTO) {
//        Merchant user = merchantService.getEntity("mobile", mobileDTO.getMobile());
//        if (null == user) {
//            throw new ServiceException(LoginCode.MobileNotExist);
//        }
//        mobileService.checkCode(CodeKey.EditPwd, user.getMobile(), mobileDTO.getCode());
//    }

    /**
     * 绑定新手机号
     *
     * @param mobileDTO
     */
//    public boolean bind(MobileDTO mobileDTO) {
//        Merchant merchant = sessionUserService.getTokenUser();
//        mobileService.checkCode(CodeKey.BindMobile, mobileDTO.getMobile(), mobileDTO.getCode());
//
//        if (null != merchantService.getEntity("mobile", mobileDTO.getMobile())) {
//            throw new ServiceException(LoginCode.MobileExist);
//        }
//
//        merchant.setMobile(mobileDTO.getMobile());
//        merchant.setPlatformMerchantId(sessionUserService.getTokenUserId());
//        return merchantService.save(merchant);
//    }

    /**
     * 重置密码
     *
     * @param resetPasswordDTO
     * @return
     */
    public Response resetPassword(ResetPasswordDTO resetPasswordDTO) {
        Merchant merchant = merchantService.getEntity("mobile",resetPasswordDTO.getMobile());
        if (merchant == null) {
            throw new ServiceException(PartnersCode.PartnersNotExist);
        }

        if(!mobileService.checkCode(CodeKey.FindPwd,resetPasswordDTO.getMobile(),resetPasswordDTO.getCode())){
            throw new ServiceException(LoginCode.CodeError);
        }
        


        DesEncrypter des = new DesEncrypter(DesEncrypter.CD_KEY);
        String password = des.encrypt(RSAUtil.simpleDecrypt(resetPasswordDTO.getPassword()));


        if(password.equals(merchant.getPassword())) {
            throw new ServiceException(LoginCode.PwdConsistent);
        }

        merchant.setPassword(password);

        boolean result =  merchantService.update(merchant);
        return result ? Response.success() : Response.failed();
    }
}
